#!/usr/bin/bash
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright 2020 Joyent, Inc.
#

# Setup for building stuff!
unset CC
unset CXX
ROOT=`pwd`
export PATH=/opt/onbld/bin:/sbin:/usr/sbin:/usr/bin:/usr/ccs/bin:/opt/SUNWspro/bin:/opt/local/bin
export SHELL=/usr/bin/bash

BUILDSTAMP=$(<${ROOT}/proto/buildstamp)
if [[ $? -ne 0 || -z "${BUILDSTAMP}" ]]; then
	printf "failed to read existing buildstamp\n" >&2
	exit 1
fi

echo "==> Building Illumos (${BUILDSTAMP})"

set -o pipefail
set -e

cd ${ROOT}/projects/illumos
[[ -d "log" ]] || mkdir -p log
gsed -i -e "s|^GATE=.*$|GATE=\"joyent_${BUILDSTAMP}\"; export GATE|" illumos.sh
if [[ -n ${MAX_JOBS} ]]; then
    MJ=${MAX_JOBS}
else
    MJ=128
fi
gsed -i -e "s|^MAX_JOBS=.*$|MAX_JOBS=${MJ}; export MAX_JOBS|" illumos.sh

#
# illumos.sh sets the value of $MAKE by default, which is used by bldenv
# and nightly. By setting MAKE below to the bootstrap dmake, illumos.sh
# will honor the one in the environment and let us solve the chicken and
# egg problem that we have.
#
export MAKE=/opt/local/bin/dmake
./usr/src/tools/scripts/bldenv illumos.sh \
    'cd $CODEMGR_WS/usr/src && export PATH="$PATH:/opt/local/bin" && \
    dmake setup && cd tools && dmake install'
export -n MAKE

printf "\nRunning illumos nightly(1).\n"
printf "This will take a while.\n"

set +e

time ./usr/src/tools/scripts/nightly illumos.sh

status=$?
if [[ $status -ne 0 ]]; then
	log_dir=$(ls -1t ./log | head -n1)
	mail_msg=$PWD/log/$log_dir/mail_msg
	nightly=$PWD/log/$log_dir/nightly.log

	#
	# Note, the blank lines at the start and end of the heredoc are
	# intentional. These make sure that the output is separate from
	# the time and eventual gmake errors.
	#
	cat << EOF

WARNING: illumos nightly build failed. Please look at the mail_msg and
nightly.log to determine the exact failure. For more information on how
to make sense of these, please see the illumos Developer's Guide section
on build failures online at:

https://www.illumos.org/books/dev/debugging.html#build-failures

The mail_msg for this build is located at:
$mail_msg

The nightly.log for this build is located at:
$nightly

If you need additional help, please reach out to the smartos-discuss
mailing list or ask in the #smartos IRC channel on Freenode.

EOF
fi
exit $status
